# Maintainer: Jelle van der Waa <jelle@archlinux.org>
# Contributor: David Runge <dvzrv@archlinux.org>
# Contributor: Radek Podgorny <radek@podgorny.cz>
# Contributor: Dan Anderson <dan-anderson at cox dptnet>

pkgname=mosquitto
pkgver=2.0.18
pkgrel=1
pkgdesc="An Open Source MQTT Broker"
arch=(loong64 x86_64)
url="https://mosquitto.org/"
license=(
  EDL-1.0
  EPL-2.0
)
depends=(
  cjson
  gcc-libs
  glibc
  openssl
  util-linux-libs
)
makedepends=(
  c-ares
  cmake
  docbook-xsl
  libwebsockets
  systemd
  uthash
)
checkdepends=(
  cunit
  python
  python-psutil
)
source=(
  https://mosquitto.org/files/source/mosquitto-$pkgver.tar.gz{,.asc}
  "$pkgname.service"
  "sysusers_mosquitto.conf"
)
backup=("etc/$pkgname/$pkgname.conf")
sha512sums=('63f7e2811964bab5856848e6918627c47afc6534ff60aad5ece3d2fa330b407c9df14027610826e343ee68ff7d8d5d93f2459713061251ded478c42766946767'
            'SKIP'
            '4789e8ee42f4a8e3ca8e7fd21cb551b5e34991e6ca1750533bbfa555260e20e8ea167bd69b99b407237bcc8969157eee792fdcf3844b839d73310a6c59e5f045'
            '21848b890c2db258138795ec21a009e022b6a8369217eb31939f976ad434229dd9f61d33e8109ade7bc001e8668e9d42b59c1ab079753860417961e102356f0e')
validpgpkeys=('A0D6EEA1DCAE49A635A3B2F0779B22DFB3E717B7')

prepare() {
  # disable broken tests
  sed '/02-subscribe-qos1/d' -i $pkgname-$pkgver/test/lib/{Makefile,test.py}
  sed '/client test/d' -i $pkgname-$pkgver/test/Makefile
}

build() {
  local cmake_options=(
    -B build
    -D CMAKE_BUILD_TYPE=None
    -D CMAKE_INSTALL_PREFIX=/usr
    -D CMAKE_INSTALL_SBINDIR=bin
    -D CMAKE_INSTALL_SYSCONFDIR=/etc
    -D WITH_BUNDLED_DEPS=OFF
    -D WITH_SRV=ON
    -D WITH_SYSTEMD=ON
    -D WITH_WEBSOCKETS=ON
    -S $pkgname-$pkgver
    -W no-dev
  )
  cmake "${cmake_options[@]}"
  cmake --build build --verbose
}

check() {
  local plugin client

  # NOTE: tests hardcode all paths... so we copy in place... -_-
  cp -v build/lib/lib* $pkgname-$pkgver/lib/
  cp -v build/lib/cpp/lib* $pkgname-$pkgver/lib/cpp/
  cp -v build/src/$pkgname $pkgname-$pkgver/src/
  for plugin in {dynamic-security,message-timestamp,payload-modification}; do
    cp -v build/plugins/$plugin/*.so $pkgname-$pkgver/plugins/$plugin/
  done
  for client in {pub,rr,sub}; do
    cp -v build/client/${pkgname}_$client $pkgname-$pkgver/client/
  done

  make -C $pkgname-$pkgver/test check
}

package() {
  depends+=(
    c-ares libcares.so
    libwebsockets libwebsockets.so
    systemd-libs libsystemd.so
  )

  DESTDIR="$pkgdir" cmake --install build

  # TODO: upstream a better systemd service file
  install -vDm 644 "$pkgname.service" -t "$pkgdir/usr/lib/systemd/system/"
  install -vDm 644 $pkgname-$pkgver/edl-v10 -t "$pkgdir/usr/share/licenses/$pkgname/"
  install -vDm 644 sysusers_mosquitto.conf "${pkgdir}"/usr/lib/sysusers.d/mosquitto.conf
}
